package cn.tedu.csmall.order.webapi.service.impl;

import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.model.Order;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.stock.service.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@DubboService
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @DubboReference
    private IStockService stockService;
    @DubboReference
    private ICartService cartService;
    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        // 1.先去减少订单中商品的库存数量(调用stock模块减少库存的方法)
        StockReduceCountDTO stockReduceCountDTO=new StockReduceCountDTO();
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockService.reduceCommodityCount(stockReduceCountDTO);
        // 2.从购物车中删除用户勾选的商品(调用cart模块删除购物车商品的方法)
        cartService.deleteUserCart(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());
        //随机异常测试seata
        if(Math.random()<0.5){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"随机异常生效");
        }
        // 3.新增订单信息
        Order order=new Order();
        BeanUtils.copyProperties(orderAddDTO,order);
        // 执行新增
        orderMapper.insertOrder(order);
        log.info("新增订单信息为:{}",order);



    }
}
